package com.orangelife.mobile.voucher.adapter;

import android.annotation.SuppressLint;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.curry.android.util.TimeUtil;
import com.curry.orangelife.mobile.R;
import com.curry.android.adapter.FatherAdapter;
import com.orangelife.mobile.constants.Constant;
import com.orangelife.mobile.util.ToastHelper;
import com.orangelife.mobile.voucher.biz.VoucherBiz;
import com.orangelife.mobile.util.DateUtil;
import com.orangelife.mobile.voucher.biz.SelectedVoucherIDListHelper;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 抵用券列表（选择模式）的适配器
 *
 * @param <T>
 */
public class VoucherListSelectAdapter<T> extends FatherAdapter<T> {
    private Context context;
    /**
     * 抵用券列表
     */
    private List<Map<String, Object>> mVoucherList;
    public static final int SHOW_TYPE_SELECT = 0;
    public static final int SHOW_TYPE_SHOW = 1;
    private int currentShowType = SHOW_TYPE_SELECT;

    @SuppressLint("UseSparseArrays")
    public VoucherListSelectAdapter(Context context, List<Map<String, Object>> list
    ) {
        this.context = context;
        this.mVoucherList = list;
    }
    // FIXME: 2016/2/29 setSelectedParamToVoucherList()这样使用数据源来保存临时选中状态是错误的，若数据源被刷新，那么新增的状态便会被清空。但是目前因为没加入下拉刷新功能，故为赶时间，可暂时如此。若将来加刷新，则需新建集合临时保存选中状态

    /** 展示类型，目前两种，可选择和不可选择 */
    public void setShowType(int showType) {
        this.currentShowType = showType;
    }

    /** 计算所有选中的抵用券的总金额（在多选模式下，目前为单选模式） */
    public String getTotalSelectedVoucherPrice() {
        List<Map<String, Object>> tempVoucherListWithSelectedStatus = mVoucherList;
        return VoucherBiz.getTotalSelectedVoucherPrice(tempVoucherListWithSelectedStatus);
    }

    /** 获取 */
    public int getTotalVoucherNum() {
        return mVoucherList.size();
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null) {
            holder = new ViewHolder();
            convertView = LayoutInflater.from(context).inflate(R.layout.item_lv_order_voucher, null);
            holder.tvPhoto = (TextView) convertView.findViewById(R.id.tvPhoto);
            holder.tvTitle = (TextView) convertView.findViewById(R.id.tvTitle);
            holder.tvChildTitle = (TextView) convertView.findViewById(R.id.tvChildTitle);
            holder.tvTime = (TextView) convertView.findViewById(R.id.tvActiveTime);
            holder.ivCheck = (ImageView) convertView.findViewById(R.id.ivCheck);
            holder.rlClick = (RelativeLayout) convertView.findViewById(R.id.rlClick);
            holder.llLayout = (LinearLayout) convertView.findViewById(R.id.llLayout);
            holder.llExpire = (LinearLayout) convertView.findViewById(R.id.llExpire);
            holder.tvRmbFlag = (TextView) convertView.findViewById(R.id.tvRmbFlag);
            holder.tvVoucherStatus = (TextView) convertView.findViewById(R.id.tvVoucherStatus);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        Map<String, Object> voucherInfoMap = mVoucherList.get(position);
//        String startTime = dateUtil.tranStringForDate(String.valueOf(voucherInfoMap.get("startTime")));
        String endTime = TimeUtil.timeStampToDate(String.valueOf(voucherInfoMap.get("endTime")), "yyyy-MM-dd");
        holder.tvPhoto.setText(String.valueOf(voucherInfoMap.get("couponValue")));
        holder.tvTitle.setText(String.valueOf(voucherInfoMap.get("couponName")));
        holder.tvChildTitle.setText("满" + String.valueOf(voucherInfoMap.get("limitValue")) + "元抵用");
        holder.tvTime.setText("有效期至:" + endTime);
//        String couponID = String.valueOf(voucherInfoMap.get("couponID"));
        if (currentShowType == SHOW_TYPE_SELECT) {
            String hasSelected = String.valueOf(voucherInfoMap.get("hasSelected"));
            selectVoucher(Boolean.parseBoolean(hasSelected), holder.ivCheck);
            holder.rlClick.setTag(R.id.tvTitle, position);
            holder.rlClick.setTag(R.id.ivCheck, holder.ivCheck);
            holder.rlClick.setTag(R.id.tvPhoto, hasSelected);
            holder.rlClick.setOnClickListener(selectVoucherListener);
        } else if (currentShowType == SHOW_TYPE_SHOW) {
            String status = String.valueOf(voucherInfoMap.get("status"));
            String statusInfo = String.valueOf(voucherInfoMap.get("statusInfo"));
            showVoucherExpireStatusInShowMode(status, holder, statusInfo);
        }
        return convertView;
    }

    private void showVoucherExpireStatusInShowMode(String status, ViewHolder holder, String statusInfo) {
        holder.tvRmbFlag.setText(Constant.RMB_FLAG);
        if ("0".equals(status)) {
            holder.llLayout.setBackgroundResource(R.drawable.voucher_bg);
            holder.tvTitle.setTextColor(context.getResources().getColor(R.color.DarkGray));
            holder.tvTime.setTextColor(context.getResources().getColor(R.color.white));
            holder.tvPhoto.setTextColor(context.getResources().getColor(R.color.lightOrange));
            holder.tvChildTitle.setTextColor(context.getResources().getColor(R.color.DarkGray));
            holder.tvRmbFlag.setTextColor(context.getResources().getColor(R.color.lightOrange));
            holder.llExpire.setVisibility(View.GONE);
        } else {
            holder.llExpire.setVisibility(View.VISIBLE);
            holder.llLayout.setBackgroundResource(R.drawable.voucher_expire_bg);
            holder.tvTitle.setTextColor(context.getResources().getColor(R.color.lightGray));
            holder.tvTime.setTextColor(context.getResources().getColor(R.color.text_grey));
            holder.tvRmbFlag.setTextColor(context.getResources().getColor(R.color.text_grey));
            holder.tvPhoto.setTextColor(context.getResources().getColor(R.color.text_grey));
            holder.tvChildTitle.setTextColor(context.getResources().getColor(R.color.text_grey));
            holder.tvVoucherStatus.setText(statusInfo);
        }
    }

    private void selectVoucher(boolean hasSelected, ImageView ivCheck) {
        if (hasSelected) {
            ivCheck.setVisibility(View.VISIBLE);
            ivCheck.setBackgroundResource(R.drawable.voucher_checked);
        } else {
            ivCheck.setVisibility(View.VISIBLE);
            ivCheck.setBackgroundResource(R.drawable.voucher_uncheck);
        }
    }

    OnClickListener selectVoucherListener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            int pos = (int) v.getTag(R.id.tvTitle);
            ImageView ivCheck = (ImageView) v.getTag(R.id.ivCheck);
            boolean hasSelected = Boolean.parseBoolean(String.valueOf(v.getTag(R.id.tvPhoto)));
            selectVoucher(hasSelected, pos, ivCheck);
        }
    };

    /** 选中抵用券 */
    private void selectVoucher(boolean hasSelected, int pos, ImageView ivCheck) {
        boolean newHasSelected = !hasSelected;
        selectVoucher(newHasSelected, ivCheck);
        VoucherBiz.updateTempVoucherSelectedStatus(mVoucherList, pos, newHasSelected, true);
        VoucherListSelectAdapter.this.notifyDataSetChanged();
        //        boolean canSelect=updateVoucherSuperpositionStatus();
    }

    /** 目前是单选模式，不需要判断叠加使用 */
    private boolean updateVoucherSuperpositionStatus() {
        //            if (newHasSelected) {
        //                canSelect = VoucherBiz.getInstance().checkVoucherSuperPositionStatusWhenSelecting(type, useType, voucherID);
        //            } else {
        //                VoucherBiz.getInstance().updateVoucherSuperPositionStatusWhenCancel(type, voucherID);
        //            }
        return false;
    }

    /**
     * Activity点击完成按钮，即选择完成，将选中的抵用券，更新该商户在VoucherBiz的已选中列表
     */
    public void finishSelectedVoucher() {
        if (currentShowType == SHOW_TYPE_SELECT) {
        /*预订单列表的商家抵用券信息一栏，需要显示金额，但是已选中抵用券列表若增加金额参数，显得多余，且与服务端接口不符，所以在这里将此商家选中的抵用券总金额传到Activity，再传回到上一个界面*/
            ArrayList<String> newSelectedVoucherList = VoucherBiz.getNewSelectedVoucherIDList(mVoucherList);
            SelectedVoucherIDListHelper.getInstance().updateCurrentSelectedVoucherIDList(newSelectedVoucherList);
//        VoucherBiz.resetVoucherSuperPositionStatus();
        }
    }

    @Override
    public int getCount() {
        return mVoucherList.size();
    }

    @Override
    public Object getItem(int position) {
        return mVoucherList == null ? 0 : mVoucherList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }


    class ViewHolder {
        /**
         * 图片上的字
         */
        private TextView tvPhoto;
        /**
         * 标题
         */
        private TextView tvTitle;
        /**
         * 子标题
         */
        private TextView tvChildTitle;
        /**
         * 时间
         */
        private TextView tvTime;
        /**
         * 选择按钮
         */
        private ImageView ivCheck;
        /**
         * item点击
         */
        private RelativeLayout rlClick;

        private LinearLayout llLayout;

        private LinearLayout llExpire;

        private TextView tvRmbFlag;

        private TextView tvVoucherStatus;/*抵用券状态*/
    }

    @SuppressLint("UseSparseArrays")
    @SuppressWarnings("unchecked")
    @Override
    public BaseAdapter setList(List<T> list) {
        this.mVoucherList = (List<Map<String, Object>>) list;
        if (currentShowType == SHOW_TYPE_SELECT) {
        /*因为目前没有下拉刷新功能，所以setList等同于唯一一次的初始化数据源，若日后加入刷新功能，则删除setSelectedParamToVoucherList()，另建集合保存临时选中状态*/
        /*初始化抵用券选中状态（已存在selfList中）和抵用券叠加关系信息*/
            ArrayList<String> selectedVoucherIDList = SelectedVoucherIDListHelper.getInstance().getSelfVoucherList();
            VoucherBiz.initTempVoucherListWithSelectedStatus(mVoucherList, selectedVoucherIDList);
        }
        return VoucherListSelectAdapter.this;
    }

}

